package org.shan.code.generator;


import org.shan.code.utils.NameUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;

/**
 * 生成entity文件
 */
public class EntityGenerator {
    // 表名
    public String tableName;
    // 列名数组
    public String[] colNames;
    // 列名类型数组
    public String[] colTypes;
    // 列名大小数组
    public int[] colSizes;
    // 列名注释
    public Map colNamesComment = new HashMap();
    // 是否需要导入包java.util.*
    public boolean needUtil = false;
    // 是否需要导入包java.sql.*
    public boolean needSql = false;
    // 是否需要导入包java.math.BigDecimal
    public boolean needBigDecimal = false;
    public static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final String SQL = "SELECT * FROM ";// 数据库操作

    // 数据库配置信息
    public static String URL;
    public static String NAME;
    public static String PASS;
    public static final String DRIVER = "com.mysql.jdbc.Driver";

    // 指定实体生成所在包的路径
    public static String basePath = new File("").getAbsolutePath();
    // 指定包名
    public static String packageOutPath = "org.herui.wushui.entity";
    // 作者名字
    public String authorName = "zzb";
    // 指定需要生成的表的表名，全部生成设置为null
    public String[] generateTables;
    // 主键
    private static String pk;


    /**
     * @description 生成class的所有内容
     */
    private String parse() {
        StringBuffer sb = new StringBuffer();
        sb.append("package " + packageOutPath + ";\r\n");
        sb.append("\r\n");
        // 判断是否导入工具包
        if (needUtil) {
            sb.append("import java.util.Date;\r\n");
        }
        if (needSql) {
            sb.append("import java.sql.*;\r\n");
        }

        for (int i = 0; i < colNames.length; i++) {
            String hasbd = sqlType2JavaType(colTypes[i]);
            if (hasbd == "BigDecimal" || "BigDecimal".equals(hasbd)) {
                needBigDecimal = true;
            }
        }
        if (needBigDecimal) {
            sb.append("import java.math.BigDecimal;\r\n");
        }

        sb.append(
                "import com.baomidou.mybatisplus.annotation.TableName;\r\n" + "import com.mlnx.common.entity.BaseEntity;\n" + "import io.swagger" + ".annotations.ApiModel;\r\n" + "import io" + ".swagger.annotations.ApiModelProperty;\r\n" + "import lombok.Data;\r\n");
        // 注释部分
        sb.append("/**\r\n");
        sb.append(" * table name:  " + tableName + "\r\n");
        sb.append(" * author name: " + authorName + "\r\n");
        sb.append(" * create time: " + SDF.format(new Date()) + "\r\n");
        sb.append(" */ \r\n");

        // 注解部分
        sb.append("@Data\r\n");
        sb.append("@ApiModel" + "\r\n");
        sb.append("@TableName(\"" + tableName + "\")\r\n");
        // 实体部分
        String classExtends = "";
        classExtends = " extends BaseEntity";

        sb.append("public class " + NameUtils.under2camel(tableName.substring(2), true) + classExtends + "{\r\n\r\n");

        processAllAttrs(sb);// 属性
        sb.append("\r\n");
        //        processConstructor(sb);//构造函数
        //        processAllMethod(sb);// get set方法
        //        processToString(sb);
        sb.append("}\r\n");
        return sb.toString();
    }

    /**
     * @param sb
     * @description 生成所有成员变量及注释
     * @author paul
     * @version V1.0
     */
    private void processAllAttrs(StringBuffer sb) {

        String[] ecInclude = {"id", "creater", "create_time", "editor", "edit_time", "remark", "status"};

        for (int i = 0; i < colNames.length; i++) {

            boolean match = false;
            String colName = colNames[i];
            for (int j = 0; j < ecInclude.length; j++) {
                if (ecInclude[j].equals(colName)) {
                    match = true;
                    break;
                }
            }
            if (match) {
                continue;
            }

            if (colNamesComment.get(colName) != null && !"".equals(colNamesComment.get(colName))) {
                sb.append("\t@ApiModelProperty(value = \"" + colNamesComment.get(colName) + "\")\r\n");
            }
            sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + NameUtils.under2camel(colName, false) + ";\r\n\r\n");
        }
    }

    /**
     * @param sb
     * @description 生成所有get/set方法
     */
    private void processAllMethod(StringBuffer sb) {
        for (int i = 0; i < colNames.length; i++) {
            sb.append("\tpublic void set" + NameUtils.initCap(colNames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " " + colNames[i] + "){\r\n");
            sb.append("\t\tthis." + colNames[i] + "=" + colNames[i] + ";\r\n");
            sb.append("\t}\r\n");
            sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + NameUtils.initCap(colNames[i]) + "(){\r\n");
            sb.append("\t\treturn " + colNames[i] + ";\r\n");
            sb.append("\t}\r\n");
        }
    }


    /**
     * @return
     * @description 查找sql字段类型所对应的Java类型
     */
    private String sqlType2JavaType(String sqlType) {
        if (sqlType.equalsIgnoreCase("bit")) {
            return "Boolean";
        } else if (sqlType.equalsIgnoreCase("tinyint")) {
            return "Byte";
        } else if (sqlType.equalsIgnoreCase("smallint")) {
            return "Short";
        } else if (sqlType.equalsIgnoreCase("int") || sqlType.equalsIgnoreCase("int unsigned")) {
            return "Integer";
        } else if (sqlType.equalsIgnoreCase("bigint")) {
            return "Long";
        } else if (sqlType.equalsIgnoreCase("float")) {
            return "Float";
        } else if (sqlType.equalsIgnoreCase("numeric") || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase(
                "money") || sqlType.equalsIgnoreCase("smallmoney")) {
            return "Double";
        } else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase(
                "nvarchar") || sqlType.equalsIgnoreCase("nchar") || sqlType.equalsIgnoreCase("text") || sqlType.equalsIgnoreCase("longtext")) {
            return "String";
        } else if (sqlType.equalsIgnoreCase("datetime")) {
            return "Date";
        } else if (sqlType.equalsIgnoreCase("image")) {
            return "Blod";
        } else if (sqlType.equalsIgnoreCase("decimal")) {
            return "BigDecimal";
        }
        return null;
    }

    /**
     * 功能：获取并创建实体所在的路径目录
     * E:\workspace\idea\lis-server\lis_api\base_api\src\main\java\org\shan\lis\device\entity
     *
     * @return
     */
    private static String pkgDirName() {
        String dirName = basePath + "\\src\\main\\java\\" + packageOutPath.replace(".", "\\");
        File dir = new File(dirName);
        if (!dir.exists()) {
            dir.mkdirs();
            System.out.println("mkdirs dir 【" + dirName + "】");
        }
        return dirName;
    }

    /**
     * @description 生成方法
     */
    void generate() throws Exception {
        // 与数据库的连接
        Connection con;
        PreparedStatement pStemt = null;
        Class.forName(DRIVER);
        con = DriverManager.getConnection(URL, NAME, PASS);
        System.out.println("connect database success..." + con);
        // 获取数据库的元数据
        DatabaseMetaData db = con.getMetaData();
        // 是否有指定生成表，有指定则直接用指定表，没有则全表生成
        List<String> tableNames = new LinkedList<>();
        if (generateTables == null) {
            // 从元数据中获取到所有的表名
            tableNames = CodeGenerator.searchTableNames("smart_watch");
        } else {
            tableNames.clear();
            for (String tableName : generateTables)
                tableNames.add(tableName);
        }
        String tableSql;
        PrintWriter pw = null;
        for (int j = 0; j < tableNames.size(); j++) {
            tableName = tableNames.get(j);
            tableSql = SQL + tableName;
            pStemt = con.prepareStatement(tableSql);
            ResultSetMetaData rsmd = pStemt.getMetaData();
            ResultSet rsk = con.getMetaData().getPrimaryKeys(con.getCatalog().toLowerCase(), null, tableName);
            if (rsk.next()) {
                String primaryKey = rsk.getString("COLUMN_NAME");
                pk = primaryKey;
            }
            int size = rsmd.getColumnCount();
            colNames = new String[size];
            colTypes = new String[size];
            colSizes = new int[size];
            // 获取所需的信息
            for (int i = 0; i < size; i++) {
                colNames[i] = rsmd.getColumnName(i + 1);
                colTypes[i] = rsmd.getColumnTypeName(i + 1);
                if (colTypes[i].equalsIgnoreCase("datetime"))
                    needUtil = true;
                if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text"))
                    needSql = true;
                colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
            }
            // 获取字段注释
            ResultSet rsComment = pStemt.executeQuery("show full columns from " + tableName);
            while (rsComment.next()) {
                colNamesComment.put(rsComment.getString("Field"), rsComment.getString("Comment"));
            }
            // 解析生成实体java文件的所有内容
            String content = parse();
            // 输出生成文件
            String dirName = EntityGenerator.pkgDirName();
            String javaPath = dirName + "/" + NameUtils.under2camel(tableName.substring(2), true) + ".java";
            FileWriter fw = new FileWriter(javaPath);
            pw = new PrintWriter(fw);
            pw.println(content);
            pw.flush();
            System.out.println("create class 【" + tableName + "】");
        }
        if (pw != null)
            pw.close();
    }

}
